package com.restkeeper.notify;

import com.alibaba.fastjson.JSONObject;
import com.restkeeper.service.CommonService;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Transaction;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * 回调
 * */
@RestController
@RequestMapping("/notify")
@Slf4j
@RequiredArgsConstructor
public class NotifyController {

    private final CommonService commonService;

    /**
     * 微信支付回调通知
     * @return
     */
    @ResponseBody
    @PostMapping("/wx_notify")
    public int weChatNotificationHandler(HttpServletRequest request, HttpServletResponse response){
        log.info("------------------------------------微信回调开始-------------------------------------");
        try {
            log.info("==================================开始解析微信回调数据==================================================");
            // 初始化 NotificationParser
            NotificationParser parser = new NotificationParser(commonService.getRSAPublicKeyNotificationConfig());
            log.info("==================================parser==================================================");
            Transaction transaction = parser.parse(getWxRequestParam(request), Transaction.class);
            log.info("==================================transaction:{}",transaction);
            if (transaction == null) {
                log.info("********************************transaction为空*****************************");
                return HttpStatus.INTERNAL_SERVER_ERROR.value();
            }
            commonService.rechargeSuccess(transaction);
        }catch (Exception e) {
            e.printStackTrace();
            log.info("********************************微信回调失败*****************************");
            return HttpStatus.INTERNAL_SERVER_ERROR.value();
        }
        return HttpStatus.OK.value();
    }

    /**
     * 微信退款回调通知
     * @return
     */
    @ResponseBody
    @PostMapping("/wx_refund_notify")
    public int wx_refund_notify(HttpServletRequest request, HttpServletResponse response){
        log.info("------------------------------------微信退款回调开始-------------------------------------");
        try {
            log.info("==================================开始解析微信退款回调数据==================================================");
            // 初始化 NotificationParser
            NotificationParser parser = new NotificationParser(commonService.getRSAPublicKeyNotificationConfig());
            log.info("==================================parser==================================================");
            Transaction transaction = parser.parse(getWxRequestParam(request), Transaction.class);
            log.info("==================================transaction:{}",transaction);
            if (transaction == null) {
                log.info("********************************transaction为空*****************************");
                return HttpStatus.INTERNAL_SERVER_ERROR.value();
            }
        }catch (Exception e) {
            e.printStackTrace();
            log.info("********************************微信退款回调失败*****************************");
            return HttpStatus.INTERNAL_SERVER_ERROR.value();
        }
        return HttpStatus.OK.value();
    }

    /**
     * 微信转账回调通知
     * @return
     */
    @ResponseBody
    @PostMapping("/wx_transfer_notify")
    public int wx_transfer_notify(HttpServletRequest request, HttpServletResponse response){
        log.info("------------------------------------微信转账回调开始-------------------------------------");
        try {
            log.info("==================================开始解析微信转账回调数据==================================================");
            // 初始化 NotificationParser
            NotificationParser parser = new NotificationParser(commonService.getRSAPublicKeyNotificationConfig());
            log.info("==================================parser==================================================");
            Transaction transaction = parser.parse(getWxRequestParam(request), Transaction.class);
            log.info("==================================transaction:{}",transaction);
            if (transaction == null) {
                log.info("********************************transaction为空*****************************");
                return HttpStatus.INTERNAL_SERVER_ERROR.value();
            }
//            commonService.refundSuccess(transaction);
        }catch (Exception e) {
            e.printStackTrace();
            log.info("********************************微信转账回调失败*****************************");
            return HttpStatus.INTERNAL_SERVER_ERROR.value();
        }
        return HttpStatus.OK.value();
    }

    @PostMapping("/ce_wx_notify")
    public int ce_wx_notify(@RequestBody Transaction transaction){
        log.info("------------------------------------微信回调开始-------------------------------------");
        try {
            if (transaction == null) {
                log.info("********************************transaction为空*****************************");
                return HttpStatus.INTERNAL_SERVER_ERROR.value();
            }
            commonService.rechargeSuccess(transaction);
        }catch (Exception e) {
            e.printStackTrace();
            log.info("********************************微信回调失败*****************************");
            return HttpStatus.INTERNAL_SERVER_ERROR.value();
        }
        return HttpStatus.OK.value();
    }



    RequestParam getWxRequestParam(HttpServletRequest request) throws IOException {
        BufferedReader br = request.getReader();
        String str = null;
        StringBuilder sb = new StringBuilder();
        while ((str = br.readLine())!=null) {
            sb.append(str);
        }
        return new RequestParam.Builder()
                .serialNumber(request.getHeader("Wechatpay-Serial"))
                .nonce(request.getHeader("Wechatpay-Nonce"))
                .signature(request.getHeader("Wechatpay-Signature"))
                .timestamp(request.getHeader("Wechatpay-Timestamp"))
                .body(String.valueOf(sb))
                .build();
    }

}
